package com.suyl.candy.impexcel.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.event.AnalysisEventListener;
import com.suyl.candy.impexcel.entity.Money;
import com.suyl.candy.impexcel.service.IMoney;
import com.suyl.candy.impexcel.utils.ExcelDemoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.function.Consumer;

/**
 * @author suyanlong
 * @version 1.0
 * @createDate 2020/4/17 22:41
 */
@RestController
@RequestMapping("/money")
@Slf4j
public class MoneyController {

    @Autowired
    IMoney iMoney;

    @PostMapping("/upload")
    public String uploadWithLambda(MultipartFile file) throws IOException {
        AnalysisEventListener<Money> moneyAnalysisEventListener = ExcelDemoUtils.getListener(this.batchInsert(), 20);
        EasyExcel.read(file.getInputStream(), Money.class, moneyAnalysisEventListener).sheet().doRead();
        return "success";
    }

    private Consumer<List<Money>> batchInsert() {
        return monies -> iMoney.saveData(monies);
    }
}
